<?php 
class Pfinal_Model_Proxy_MasterSlave implements Pfinal_Model_Proxy_Strategy{
	
	protected $masterAdapters;
	
	protected $slaveAdapters;
	
	protected $adapter;
	
	public function __construct($dbConf,$adapter = 'mysql'){
		if (empty($dbConf)){
			throw new Pfinal_Exception_Argument("invalid master/slave dbconf", -1);
		}
		$this->adapter = $adapter;
		
		if (isset($dbConf['master'])&&!empty($dbConf['master'])){
			foreach ($dbConf['master'] as $conf){
				$this->cacheConnection($conf,$this->masterAdapters);
			}
		}
		if (isset($dbConf['slave'])&&!empty($dbConf['slave'])){
			foreach ($dbConf['slave'] as $conf){
				$this->cacheConnection($conf,$this->slaveAdapters);
			}
		}
		
	}
	
	/* (non-PHPdoc)
	 * @see Pfinal_Model_Proxy_Strategy::getAdapterProxy()
	 */
	public function getAdapterProxy(Pfinal_Model_Statement $stm) {
		// TODO Auto-generated method stub
		if ($stm instanceof Pfinal_Model_Selector){
			shuffle($this->slaveAdapters);
			$adapter = end($this->slaveAdapters);
			
		}
		
		if ($stm instanceof Pfinal_Model_Update || $stm instanceof Pfinal_Model_Insert || $stm instanceof Pfinal_Model_DDL){
			shuffle($this->masterAdapters);
			$adapter = end($this->masterAdapters);
		}
		return $adapter;
	}

	protected function cacheConnection($conf,&$pool){
		if (!is_array($pool)){
			$pool = array();
		}
		$host = $conf['host'];
		$port = $conf['port'];
		$user = $conf['user'];
		$passwd = $conf['passwd'];
		$database = $conf['database'];
		$instance = null;
		switch ($this->adapter){
			case 'mysql':
			default:
				$instance = new Pfinal_Model_Adapter_RMDBS();
				$instance->init($conf);
				break;
			
		}
		if (null===$instance){
			throw new Pfinal_Exception_Argument("unknow adaptername:{$this->adapter}", -1);
		}
		$key = md5(sprintf('%s:%s:%s:%s:%s',$host,$port,$user,$passwd,$database));
		$pool[$key] = $instance;
	}
	
}